import { useState, useEffect } from "react";
import { Box } from "@mui/material";
import { useForm } from "react-hook-form";
import { gql, useLazyQuery, useMutation } from "@apollo/client";
import Form from "components/User/Form";
import toast from "react-hot-toast";
import { signIn } from "next-auth/react";
import TabsControl from "components/Auth/TabsControl";
import TabPanel from "components/Auth/TabPanel";
import crypto from "crypto";
import BaseCard from "components/BaseCard";
import CenterWrap from "components/CenterWrap";
import BorderCard from "components/BorderCard";
import OAuthPanel from "components/Auth/OAuthPanel";

/* 定义邮箱验证查询 */
const EMAIL_VERIFY = gql`
  query Query($email: String!) {
    verifyEmail(email: $email)
  }
`;

export default function SignUp() {
  const [verifyEmail, { data, error }] = useLazyQuery(EMAIL_VERIFY);
  const [value, setValue] = useState(0);

  /* tab 配置 */
  const tab = {
    tabs: ["登录", "注册"],
    value,
    handleChange(event: React.SyntheticEvent, newValue: number) {
      setValue(newValue);
    },
  };
  /* 登录 表单配置 */
  const signInForm = {
    title: "登录",
    btnTitle: "登录",
    onSubmit: async ({ email, password }) => {
      // 加密传输
      password = crypto.createHash("md5").update(password).digest("hex");
      toast.promise(
        signIn("credentials", { email, password, callbackUrl: "/" }),
        {
          loading: "正在登录",
          success: "登录成功",
          error: "登录失败，请检查下账号密码",
        }
      );
    },
    options: [
      {
        name: "email",
        label: "邮箱",
        required: true,
        setting: {
          pattern: {
            value:
              /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/,
            message: "请输入正确的邮箱格式",
          },
          required: true,
        },
      },
      {
        name: "password",
        label: "密码",
        type: "password",
        required: true,
        setting: {
          required: true,
        },
      },
    ],
  };
  /* 注册 表单配置 */
  const signUpForm = {
    title: "注册",
    btnTitle: "继续",
    onSubmit: async (formData) => {
      // console.log(formData);
      // 步骤一：验证邮箱
      const { email } = formData;
      toast.promise(verifyEmail({ variables: { email } }), {
        loading: "正在校验",
        success: ({ data: { verifyEmail } }) => {
          // 若可用切换到步骤2
          if (!verifyEmail) {
            signIn("email", {
              email,
              callbackUrl: "/auth/new-user",
            });
          }
          return verifyEmail
            ? "邮箱已注册"
            : "邮箱可用，已发送注册链接，请打开邮箱继续下一步";
        },
        error: "验证失败",
      });
    },
    options: [
      {
        name: "email",
        label: "邮箱",
        required: true,
        setting: {
          pattern: {
            value:
              /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/,
            message: "请输入正确的邮箱格式",
          },
          required: true,
        },
      },
    ],
  };
  /* 渲染 */
  return (
    <CenterWrap
      title="登录/注册"
      sx={{
        minHeight: "500px",
      }}
    >
      <BorderCard
        sx={{
          width: {
            md: 2 / 3,
            sm: 3 / 5,
            xs: 1,
          },
          p: 4,
        }}
      >
        <Box>
          <TabsControl {...tab}>
            <TabPanel value={value} index={0}>
              <Form {...signInForm} />
            </TabPanel>
            <TabPanel value={value} index={1}>
              <Form {...signUpForm} />
            </TabPanel>
          </TabsControl>
        </Box>
        <OAuthPanel />
      </BorderCard>
    </CenterWrap>
  );
}
